/* global  expect, apiTest */

require('../../apiTest')
const App = {}

// 权限列表
App.typeHook = [
  'staffInfo',
  'staffPasswd'
]

App.typeApi = [
  'login',
  'staffFind',
  'staffFindOne'
]

// 列表单条验证
App.checkOne = function(v, post) {
  expect(v).to.be.an('object')
  apiTest.isObjectId(v._id)
  expect(v.name).to.be.an('string')
  if (v.mark) expect(v.mark).to.be.an('string')
  if (v.secret) expect(v.secret).to.be.an('string')
  if (v.gateway) expect(v.gateway).to.be.an('string')
  if (v.hooks) expect(v.hooks).to.be.an('array')
  if (v.apis) expect(v.apis).to.be.an('array')
  if (v.enable) expect(v.enable).to.be.an('boolean')
  if (post) {
    Object.keys(post).forEach((key) => {
      expect(v[key]).to.deep.equal(post[key])
    })
  }
}

// 列表通用验证
App.checkList = function(get, cb) {
  return apiTest.get('/app/find', Object.assign({}, get))
    .then(function(res) {
      var data = apiTest.apiOk(res)
      expect(data).to.be.a('object')
      // 验证分页
      apiTest.checkPaging(data)
      data.list.forEach(function(v) {
        App.checkOne(v)
        if (cb) cb(v)
      })
    })
}

// 生成随机提交数据
App.randOne = function() {
  return {
    name: 'autoTest' + (new Date()).getTime(),
    gateway: 'http://gateway.com/' + (new Date()).getTime(),
    hooks: apiTest.ranArr(App.typeHook, 0, 2),
    apis: apiTest.ranArr(App.typeApi, 0, 3),
    enable: true
  }
}

// 删除应用
App.removeOne = function(_id, cb) {
  return apiTest.post('/app/remove', { _id: _id }).then(function(res) {
    var data = apiTest.apiOk(res)
    expect(data.ok).to.equal(1)
    let num = 1
    if (Array.isArray(_id)) num = _id.length
    expect(data.n).to.equal(num)
    if (cb) return cb()
  })
}
// 操作应用
App.enableOne = function(_id, val, cb) {
  return apiTest.post('/app/enable', { _id: _id, enable: val }).then(function(res) {
    var data = apiTest.apiOk(res)
    expect(data.ok).to.equal(1)
    let num = 1
    if (Array.isArray(_id)) num = _id.length
    expect(data.n).to.equal(num)
    if (cb) return cb()
  })
}
// 修改用户并查询验证
App.editOne = function(_id, cb) {
  var post = App.randOne()
  post._id = _id
  return apiTest.post('/app/update?_id=' + _id, post).then(function(res) {
    apiTest.apiOk(res)
    // 查
    return apiTest.get('/app/findOne', { _id: _id }).then(function(res) {
      var data = apiTest.apiOk(res)
      App.checkOne(data, post)
      if (cb) return cb(post)
    })
  })
}

module.exports = App
